package model

import (
	"errors"
	"time"
)

type Post struct {
	Id        int64
	Uid       int64
	CreatedAt time.Time `xorm:"created"`
	UpdatedAt time.Time `xorm:"updated"`
	Enable    bool
	Title     string
	SubTitle  string
	Content   string `xorm:"text"`
	Pics      []string
	Module    string
	Author    string
	Like      int32
}

func (p *Post) OneById() error {
	ok, err := orm.ID(p.Id).Get(p)
	if !ok {
		return errors.New(PostNotFound)
	}
	return err
}

func (p *Post) OneByModule() error {
	if p.Module == "" {
		return errors.New(PostNotFound)
	}

	ok, err := orm.Where("module = ?", p.Module).Desc("id").Get(p)
	if !ok {
		return errors.New(PostNotFound)
	}
	return err
}

func (p *Post) Page(num, size int32, desc bool, order string) ([]Post, error) {
	length := int(size)
	start := (int(num) - 1) * length
	if length == 0 {
		length = 5
	}
	var posts []Post
	o := orm.Limit(length, start)
	if order == "" {
		order = "id"
	}
	if p.Enable {
		o.Where("enable = ?", true)
	}
	if p.Module != "" {
		o.And("module = ?", p.Module)
	}
	if p.Uid > 0 {
		o.And("uid = ?", p.Uid)
	}
	if desc {
		o.Desc(order)
	} else {
		o.Asc(order)
	}
	err := o.Find(&posts)
	return posts, err
}

func (p *Post) Count() (int64, error) {
	o := orm.Where("id > ?", 0)
	if p.Enable {
		o = o.And("enable = ?", true)
	}
	if p.Module != "" {
		o.And("module = ?", p.Module)
	}
	return o.Count(p)
}

func (p *Post) Create() error {
	ok, err := orm.Insert(p)
	if ok == 0 {
		return errors.New(PostCreateFailed)
	}
	return err
}

func (p *Post) EnableCheck() error {
	if !p.Enable {
		return errors.New(PostDisabled)
	}
	return nil
}

func (p *Post) Toggle() error {
	p.Enable = !p.Enable
	ok, err := orm.ID(p.Id).Cols("enable").Update(p)
	if ok == 0 {
		return errors.New(PostEditFailed)
	}
	return err
}
